package com.itheima.reggie.common;

import com.itheima.reggie.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//需要设置全局异常的类
@RestControllerAdvice(annotations = {Controller.class, RestController.class})
@Slf4j
public class GlobalExceptionHandler {

    //需要处理的异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R HandleException(SQLIntegrityConstraintViolationException exception) {
        String message = exception.getMessage();
        log.info("出现了sql异常:{}", message);
        //处理异常
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String msg=split[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知异常");

    }


    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
